package com.knife.interfaces.extension.service.impl;

import com.knife.common.utils.KnifeStringUtil;
import com.knife.interfaces.extension.config.AmapKeyProperties;
import com.knife.interfaces.extension.dto.AmapIpV1;
import com.knife.interfaces.extension.dto.AmapIpV2;
import com.knife.interfaces.extension.service.IpAddressService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author tianhao.luo@hand-china.com
 * @version 1.0
 * @date 2022年03月09日 星期三 8:26 下午
 * @description
 * @since 1.0
 */
@Service
//@ConditionalOnBean(value = {RestTemplate.class,AmapKeyProperties.class}) 疑问：加了之后无法注入
public class IpAddressServiceImpl implements IpAddressService {

    @Autowired
    private RestTemplateBuilder restTemplateBuilder;

    @Autowired
    private AmapKeyProperties amapKeyProperties;

    @Override
    public AmapIpV1 obtainRealLocationV1(String ip) {
        if (StringUtils.isEmpty(ip)){
            return null;
        }
        String url = KnifeStringUtil.resolveStr(amapKeyProperties.getV1().getArgs(), amapKeyProperties.getV1().getUrl()) + ip;
        RestTemplate restTemplate = restTemplateBuilder.build();
        ResponseEntity<AmapIpV1> entity = restTemplate.getForEntity(url, AmapIpV1.class);

        if (HttpStatus.OK.equals(entity.getStatusCode())) {
            return entity.getBody();
        }
        return null;
    }

    @Override
    public AmapIpV2 obtainRealLocationV2(String ip) {
        if (StringUtils.isEmpty(ip)){
            return null;
        }
        String url = KnifeStringUtil.resolveStr(amapKeyProperties.getV2().getArgs(), amapKeyProperties.getV2().getUrl()) + ip;
        RestTemplate restTemplate = restTemplateBuilder.build();
        ResponseEntity<AmapIpV2> entity = restTemplate.getForEntity(url, AmapIpV2.class);
        if (HttpStatus.OK.equals(entity.getStatusCode())) {
            return entity.getBody();
        }
        return null;
    }
}
